package services

import (
	"fmt"

	"github.com/astaxie/beego"
	"github.com/go-xorm/core"
	"github.com/go-xorm/xorm"
	_ "github.com/lib/pq"
)

const (
	driverName     = "driverName"
	dataSourceName = "dataSourceName"
	driverNameStr  = "postgres"
	dataSourceStr  = "user=gocommerce dbname=goCommerce password=P@ssw0rd sslmode=disable"
)

var dbEngine *xorm.Engine

//init db engine
func init() {
	driverStr, dataSourceStr := initDbConnStrs()
	fmt.Println("driverStr : ", driverStr)
	fmt.Println("dataSourceStr : ", dataSourceStr)
	dbEngine, _ = xorm.NewEngine(driverStr, dataSourceStr)
	if dbEngine == nil {
		panic("xorm engine init fault !")
	}
	dbEngine.ShowSQL(true)
	dbEngine.Logger().SetLevel(core.LOG_DEBUG)
}

//init db connection settings
func initDbConnStrs() (string, string) {
	driverStr := beego.AppConfig.String(driverName)
	sourceStr := beego.AppConfig.String(dataSourceName)
	if driverStr == "" || dataSourceStr == "" {
		return driverNameStr, dataSourceStr
	}
	return driverStr, sourceStr
}
